package com.bnq.control.desktop.xmlview;

import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;

public class XmlView implements OnClickListener, OnTouchListener {

	private View mSelfView;
	private OnSubViewClickListener mSubViewClickListener;
	private OnPrepareViewDelegate mOnPrepareViewDelegate;
	private OnSubViewTouchListener mOnSubViewTouchListener;
	private Object mSender;

	public XmlView(View selfView) {
		super();
		mSelfView = selfView;
		onInitView(mSelfView);
	}

	private void onInitView(View rootView) {
		onInitClickView(rootView, this);
		onInitTouchView(rootView, this);
	}

	protected void onInitClickView(View rootView, OnClickListener l) {

	}

	protected void onInitTouchView(View rootView, OnTouchListener l) {

	}

	/**
	 * Set the enabled state of this view.
	 *
	 * @param visibility
	 *            One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
	 */
	public void setVisibility(int visibility) {
		if (View.VISIBLE == visibility && null != mOnPrepareViewDelegate) {
			Object sender = mSender;
			if (null == sender) {
				sender = this;
			}
			mOnPrepareViewDelegate.onPrepareView(sender, mSelfView);
		}
		mSelfView.setVisibility(visibility);
	}

	@Override
	public void onClick(View v) {
		if (null != mSubViewClickListener) {
			Object sender = mSender;
			if (null == sender) {
				sender = this;
			}
			mSubViewClickListener.onSubViewClick(sender, v);
		}
	}

	public void setOnSubViewClickListener(OnSubViewClickListener l) {
		mSubViewClickListener = l;
	}

	public void setOnPrepareViewDelegate(OnPrepareViewDelegate delegate) {
		mOnPrepareViewDelegate = delegate;
	}

	public void setOnSubViewTouchListener(OnSubViewTouchListener l) {
		mOnSubViewTouchListener = l;
	}

	public void show() {
		setVisibility(View.VISIBLE);
	}

	public void hide() {
		setVisibility(View.GONE);
	}

	public void setSender(Object sender) {
		mSender = sender;
	}

	public boolean isShow() {
		return View.VISIBLE == mSelfView.getVisibility();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (null != mOnSubViewTouchListener) {
			Object sender = mSender;
			if (null == sender) {
				sender = this;
			}
			return mOnSubViewTouchListener.onSubViewTouch(sender, v, event);
		}
		return false;
	}

	public View getView() {
		return mSelfView;
	}

	public boolean performSubViewClick(int vId) {
		View rootView = getView();
		View v = rootView.findViewById(vId);
		if (null != v) {
			return v.performClick();
		}
		return false;
	}

}
